package com.wing.product.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.annotation.RequestObjectFieldIgnore;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.product.model.entity.WarehouseProductMark;
import com.wing.product.model.entity.WarehouseProductMarkPrice;
import com.wing.product.service.WarehouseProductMarkPriceService;
import com.wing.product.service.WarehouseProductMarkService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Api(value = "云仓", tags = "#/warehouseFactory/product/warehouseProductMark")
@RestController("WarehouseProductMarkController")
@RequestMapping("/warehouse/admin/productMark")
@RequiredArgsConstructor
public class WarehouseProductMarkController {

    private final WarehouseProductMarkService warehouseProductBrandService;

    @Autowired
    private WarehouseProductMarkPriceService warehouseProductMarkPriceService;


    @ApiOperation(value = "查询所有牌号", notes = "搜索")
    @GetMapping("/list")
    public PageResult<WarehouseProductMark> list(
            @RequestParam(value = "page", defaultValue = "1", required = false) Integer page
            ,@RequestParam(value = "limit", defaultValue = "10", required = false) Integer limit
            ,@RequestParam(value = "sort", defaultValue = "create_time", required = false) String sort
            ,@RequestParam(value = "order", defaultValue = "asc", required = false) String order,
            String markName,
            String markCode
    ){

        Page<WarehouseProductMark> pg = new Page<>(page, limit);
        Map paramMap=new HashMap();
        paramMap.put("sort", StrUtil.toUnderlineCase(sort));
        paramMap.put("order", order);
        paramMap.put("varietyName", markName);
        paramMap.put("varietyCode", markCode);
        //搜索
        IPage<WarehouseProductMark> list = warehouseProductBrandService.pageList4app(pg,paramMap);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }

    @ApiOperation(value = "添加牌号", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    public JsonResult add(@RequestBody WarehouseProductMark warehouseProductBrand)  {
        try{
            return warehouseProductBrandService.saveWarehouseProductBrand(warehouseProductBrand);
        }catch (Exception e){
            return JsonResult.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "修改牌号", notes = "修改")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PutMapping("/update")
    public JsonResult update(@RequestBody WarehouseProductMark warehouseProductBrand)  {
        try{
            return warehouseProductBrandService.update(warehouseProductBrand);
        }catch (Exception e){
            return JsonResult.fail(e.getMessage());
        }
    }


    @ApiOperation(value = "删除牌号", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Id", value = "品种id", required = true, dataType = "Integer", paramType = "path")
    })
    @DeleteMapping("/{id}" )
    public JsonResult delete(@PathVariable("id") Long warehouseProductVarietyId) {
        return warehouseProductBrandService.deleteWarehouseProductBrand(warehouseProductVarietyId);
    }

    @ApiOperation(value = "添加牌号价格", notes = "添加")
    @PostMapping("/addPrice")
    public JsonResult addPrice(@RequestBody WarehouseProductMarkPrice warehouseProductMarkPrice)  {
        try{
            return warehouseProductMarkPriceService.saveWarehouseProductMarkPrice(warehouseProductMarkPrice);
        }catch (Exception e){
            return JsonResult.fail(e.getMessage());
        }
    }


    @ApiOperation(value = "查询所有牌号", notes = "搜索")
    @GetMapping("/priceList")
    public PageResult<WarehouseProductMark> priceList(
            @RequestParam(value = "page", defaultValue = "1", required = false) Integer page
            ,@RequestParam(value = "limit", defaultValue = "10", required = false) Integer limit
            ,@RequestParam(value = "sort", defaultValue = "create_time", required = false) String sort
            ,@RequestParam(value = "order", defaultValue = "asc", required = false) String order,
String markId
    ){

        Page<WarehouseProductMark> pg = new Page<>(page, limit);
        Map paramMap=new HashMap();
        paramMap.put("sort", StrUtil.toUnderlineCase(sort));
        paramMap.put("order", order);
        paramMap.put("markId", markId);
        //搜索
        IPage<WarehouseProductMark> list = warehouseProductMarkPriceService.pageList4app(pg,paramMap);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }

    @ApiOperation(value = "校验价格", notes = "搜索")
    @GetMapping("/computePrice")
    public JsonResult computePrice(
            @Param("diameter")String diameter,//厚
            @Param("warehouseLength")String warehouseLength, //长度
            @Param("type")String type,//类型 厚度1 长度2 包装3
            @Param("processId")String processId,//工艺id
            @Param("markId")String markId,//牌号id
            @Param("count")double count//子捆包数
    ){
        double p=0.0;

        Map labelName=warehouseProductMarkPriceService.findLabelName(processId);

        if(labelName.get("label_name").toString().equals("横切开平")){
            Map map =warehouseProductMarkPriceService.computePriceDiameter("1",processId,markId,diameter);
            if(map.get("diameterPrice").toString().equals("0")){
                return JsonResult.fail("厚度价格未找到",p);
            }
            Map map1 =warehouseProductMarkPriceService.computePriceLength("2",processId,markId,warehouseLength);
            if(map1.get("lengthPrice").toString().equals("0")){
                return JsonResult.fail("长度价格未找到",p);
            }
            p=Double.parseDouble(map.get("diameterPrice").toString())+Double.parseDouble(map1.get("lengthPrice").toString());
            return JsonResult.success(p);
        }else if(labelName.get("label_name").toString().equals("纵切收卷")){
            Map map =warehouseProductMarkPriceService.computePriceDiameter("1",processId,markId,diameter);
            if(map.get("diameterPrice").toString().equals("0")){
                return JsonResult.fail("厚度价格未找到",p);
            }
            Map map1 =warehouseProductMarkPriceService.findBundle("2",processId,markId);
            if(map1.get("unit_price").toString().equals("-1")){
                return JsonResult.fail("长度价格未找到",p);
            }
            //TODO 根据实际数量对比数据库的最大值判断数量*价格
            if(Double.parseDouble(map1.get("upperThreshold").toString())<count && !map1.get("unit_price").toString().equals("0")){
                //最大值
                double maxCount=Double.parseDouble(map1.get("upperThreshold").toString());
                //每条单价
                double countPrice=Double.parseDouble(map1.get("unit_price").toString());
                //差价
                double sumPrice=(count-maxCount)*countPrice;
                //最终差价
                p=Double.parseDouble(map.get("diameterPrice").toString())+(sumPrice/count);
            }else{
                p=Double.parseDouble(map.get("diameterPrice").toString());
            }
            return JsonResult.success(p);
        }else if(labelName.get("label_name").toString().equals("纵切开平")){
            Map map =warehouseProductMarkPriceService.computePriceDiameter("1",processId,markId,diameter);
            if(map.get("diameterPrice").toString().equals("0")){
                return JsonResult.fail("厚度价格未找到",p);
            }
            p=Double.parseDouble(map.get("diameterPrice").toString());
            return JsonResult.success(p);
        }
        return JsonResult.fail("计算失败");
    }

    @ApiOperation(value = "校验价格", notes = "搜索")
    @GetMapping("/computeWeight")
    public JsonResult computeWeight(
            double diameter,//厚
            double length, //长度
            double weight,
            String markId
    ){
        Map map =warehouseProductMarkPriceService.findMark(markId);
        if(!map.isEmpty()){
            double res=(diameter*length*weight)/10*Double.parseDouble(map.get("density").toString());
            // 4. 转换为吨（1 kg = 1000 g, 1 t = 1000 kg → 1 t = 1,000,000 g）
            double massTons = res / 1_000_000;
            return JsonResult.success(massTons);
        }else{
            return JsonResult.fail("密度为空");
        }
    }


}
